import Mock from 'mockjs'

// 设置延迟时间
Mock.setup({
  timeout: '200-600'
})

// 随机图片地址
const imageUrls = [
  'https://picsum.photos/300/300?random=1',
  'https://picsum.photos/300/300?random=2',
  'https://picsum.photos/300/300?random=3',
  'https://picsum.photos/300/300?random=4',
  'https://picsum.photos/300/300?random=5',
  'https://picsum.photos/300/300?random=6',
  'https://picsum.photos/300/300?random=7',
  'https://picsum.photos/300/300?random=8',
  'https://picsum.photos/300/300?random=9',
  'https://picsum.photos/300/300?random=10',
  'https://picsum.photos/300/300?random=11',
  'https://picsum.photos/300/300?random=12',
  'https://picsum.photos/300/300?random=13',
  'https://picsum.photos/300/300?random=14',
  'https://picsum.photos/300/300?random=15',
  'https://picsum.photos/300/300?random=16',
  'https://picsum.photos/300/300?random=17',
  'https://picsum.photos/300/300?random=18',
  'https://picsum.photos/300/300?random=19',
  'https://picsum.photos/300/300?random=20'
]

// 全局数据存储
let globalProducts = []
let globalCategories = []
let globalUsers = []
let globalOrders = []
let globalAddresses = []

// 用户相关数据存储
let userFavorites = {} // 用户收藏数据 { userId: [favorites] }
let userCarts = {} // 用户购物车数据 { userId: [cartItems] }

// 初始化全局数据
const initializeGlobalData = () => {
  console.log('Mock: 开始初始化全局数据...')
  
  // 生成商品分类
  globalCategories = [
    { id: 1, name: '手机数码', icon: '📱', description: '智能手机、平板电脑等数码产品' },
    { id: 2, name: '电脑办公', icon: '💻', description: '笔记本电脑、台式机、办公设备' },
    { id: 3, name: '家用电器', icon: '🏠', description: '冰箱、洗衣机、空调等家电' },
    { id: 4, name: '服装鞋帽', icon: '👕', description: '男装、女装、童装、鞋帽配饰' },
    { id: 5, name: '美妆护肤', icon: '💄', description: '化妆品、护肤品、香水等' },
    { id: 6, name: '食品生鲜', icon: '🍎', description: '零食、饮料、生鲜食品' },
    { id: 7, name: '运动户外', icon: '🏃', description: '运动鞋服、健身器材、户外用品' },
    { id: 8, name: '图书音像', icon: '📚', description: '图书、音像制品、电子书' }
  ]
  
  // 生成商品数据
  globalProducts = generateProducts(50)
  
  // 生成固定用户数据
  globalUsers = [
    {
      id: 1,
      username: 'admin',
      email: 'admin@example.com',
      phone: '13800138001',
      avatar: 'https://picsum.photos/100/100?random=1',
      gender: 'male',
      birthday: '1990-01-01',
      bio: '系统管理员',
      address: {
        name: '张三',
        phone: '13800138001',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        detail: '三里屯SOHO 1号楼'
      },
      createTime: '2024-01-01 00:00:00'
    },
    {
      id: 2,
      username: 'user001',
      email: 'user001@example.com',
      phone: '13800138002',
      avatar: 'https://picsum.photos/100/100?random=2',
      gender: 'female',
      birthday: '1992-05-15',
      bio: '热爱购物的用户',
      address: {
        name: '李四',
        phone: '13800138002',
        province: '上海市',
        city: '上海市',
        district: '浦东新区',
        detail: '陆家嘴金融中心'
      },
      createTime: '2024-01-02 10:30:00'
    },
    {
      id: 3,
      username: 'user002',
      email: 'user002@example.com',
      phone: '13800138003',
      avatar: 'https://picsum.photos/100/100?random=3',
      gender: 'male',
      birthday: '1988-12-20',
      bio: '数码产品爱好者',
      address: {
        name: '王五',
        phone: '13800138003',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detail: '科技园南区'
      },
      createTime: '2024-01-03 14:20:00'
    },
    {
      id: 4,
      username: 'user003',
      email: 'user003@example.com',
      phone: '13800138004',
      avatar: 'https://picsum.photos/100/100?random=4',
      gender: 'female',
      birthday: '1995-08-10',
      bio: '时尚达人',
      address: {
        name: '赵六',
        phone: '13800138004',
        province: '江苏省',
        city: '南京市',
        district: '鼓楼区',
        detail: '新街口商圈'
      },
      createTime: '2024-01-04 09:15:00'
    },
    {
      id: 5,
      username: 'user004',
      email: 'user004@example.com',
      phone: '13800138005',
      avatar: 'https://picsum.photos/100/100?random=5',
      gender: 'male',
      birthday: '1991-03-25',
      bio: '运动健身爱好者',
      address: {
        name: '孙七',
        phone: '13800138005',
        province: '浙江省',
        city: '杭州市',
        district: '西湖区',
        detail: '西溪湿地附近'
      },
      createTime: '2024-01-05 16:45:00'
    },
    {
      id: 6,
      username: 'user005',
      email: 'user005@example.com',
      phone: '13800138006',
      avatar: 'https://picsum.photos/100/100?random=6',
      gender: 'female',
      birthday: '1993-11-08',
      bio: '美食爱好者',
      address: {
        name: '周八',
        phone: '13800138006',
        province: '四川省',
        city: '成都市',
        district: '锦江区',
        detail: '春熙路步行街'
      },
      createTime: '2024-01-06 11:30:00'
    },
    {
      id: 7,
      username: 'user006',
      email: 'user006@example.com',
      phone: '13800138007',
      avatar: 'https://picsum.photos/100/100?random=7',
      gender: 'male',
      birthday: '1989-07-12',
      bio: '科技发烧友',
      address: {
        name: '吴九',
        phone: '13800138007',
        province: '北京市',
        city: '北京市',
        district: '海淀区',
        detail: '中关村科技园'
      },
      createTime: '2024-01-07 13:20:00'
    },
    {
      id: 8,
      username: 'user007',
      email: 'user007@example.com',
      phone: '13800138008',
      avatar: 'https://picsum.photos/100/100?random=8',
      gender: 'female',
      birthday: '1994-04-18',
      bio: '文艺青年',
      address: {
        name: '郑十',
        phone: '13800138008',
        province: '上海市',
        city: '上海市',
        district: '黄浦区',
        detail: '外滩附近'
      },
      createTime: '2024-01-08 15:10:00'
    },
    {
      id: 9,
      username: 'user008',
      email: 'user008@example.com',
      phone: '13800138009',
      avatar: 'https://picsum.photos/100/100?random=9',
      gender: 'male',
      birthday: '1990-09-30',
      bio: '游戏玩家',
      address: {
        name: '陈十一',
        phone: '13800138009',
        province: '广东省',
        city: '广州市',
        district: '天河区',
        detail: '珠江新城'
      },
      createTime: '2024-01-09 12:00:00'
    },
    {
      id: 10,
      username: 'user009',
      email: 'user009@example.com',
      phone: '13800138010',
      avatar: 'https://picsum.photos/100/100?random=10',
      gender: 'female',
      birthday: '1996-02-14',
      bio: '学生党',
      address: {
        name: '林十二',
        phone: '13800138010',
        province: '江苏省',
        city: '苏州市',
        district: '姑苏区',
        detail: '平江路古街'
      },
      createTime: '2024-01-10 08:30:00'
    }
  ]
  
  // 生成订单数据
  globalOrders = generateOrders(30)
  
  // 为每个用户生成初始收藏和购物车数据
  globalUsers.forEach(user => {
    // 为每个用户生成一些随机收藏
    const userFavCount = Mock.Random.integer(0, 8)
    userFavorites[user.id] = []
    
    for (let i = 0; i < userFavCount; i++) {
      const randomProduct = globalProducts[Math.floor(Math.random() * globalProducts.length)]
      if (randomProduct && !userFavorites[user.id].find(f => f.id === randomProduct.id)) {
        userFavorites[user.id].push({
          id: randomProduct.id,
          name: randomProduct.name,
          description: randomProduct.description,
          price: randomProduct.price,
          originalPrice: randomProduct.originalPrice,
          images: randomProduct.images,
          rating: randomProduct.rating,
          reviews: randomProduct.reviews,
          stock: randomProduct.stock,
          addTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
        })
      }
    }
    
    // 为每个用户生成一些随机购物车数据
    const userCartCount = Mock.Random.integer(0, 5)
    userCarts[user.id] = []
    
    for (let i = 0; i < userCartCount; i++) {
      const randomProduct = globalProducts[Math.floor(Math.random() * globalProducts.length)]
      if (randomProduct && !userCarts[user.id].find(c => c.id === randomProduct.id)) {
        userCarts[user.id].push({
          id: randomProduct.id,
          name: randomProduct.name,
          price: randomProduct.price,
          originalPrice: randomProduct.originalPrice,
          images: randomProduct.images,
          stock: randomProduct.stock,
          quantity: Mock.Random.integer(1, 3),
          addTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
        })
      }
    }
  })
  
  // 生成地址数据
  globalAddresses = generateAddresses(5)
  
  console.log('Mock: 全局数据初始化完成')
  console.log('Mock: 商品数量:', globalProducts.length)
  console.log('Mock: 分类数量:', globalCategories.length)
  console.log('Mock: 用户数量:', globalUsers.length)
  console.log('Mock: 订单数量:', globalOrders.length)
}

// 商品分类 (使用全局数据)
const getCategories = () => globalCategories

// 生成商品数据
const generateProducts = (count = 50) => {
  const products = []
  
  for (let i = 0; i < count; i++) {
    const category = globalCategories[Math.floor(Math.random() * globalCategories.length)]
    const originalPrice = Mock.Random.float(50, 2000, 2, 2)
    const discount = Mock.Random.float(0.1, 0.8, 2, 2)
    const currentPrice = originalPrice * discount
    
    products.push({
      id: i + 1,
      name: Mock.Random.ctitle(5, 15),
      description: Mock.Random.cparagraph(2, 4),
      price: currentPrice,
      originalPrice: originalPrice,
      category: category.name,
      categoryId: category.id,
      images: [
        imageUrls[Math.floor(Math.random() * imageUrls.length)],
        imageUrls[Math.floor(Math.random() * imageUrls.length)],
        imageUrls[Math.floor(Math.random() * imageUrls.length)]
      ],
      rating: Mock.Random.float(3.0, 5.0, 1, 1),
      reviews: Mock.Random.integer(10, 2000),
      stock: Mock.Random.integer(0, 100),
      sales: Mock.Random.integer(0, 5000),
      specifications: {
        '品牌': Mock.Random.pick(['Apple', 'Samsung', 'Nike', 'Adidas', '华为', '小米', 'OPPO', 'VIVO']),
        '型号': Mock.Random.string('upper', 5, 8),
        '颜色': Mock.Random.pick(['黑色', '白色', '红色', '蓝色', '绿色', '黄色', '紫色', '粉色']),
        '尺寸': Mock.Random.pick(['S', 'M', 'L', 'XL', 'XXL']),
        '材质': Mock.Random.pick(['棉质', '涤纶', '丝绸', '皮革', '金属', '塑料']),
        '重量': Mock.Random.float(0.1, 5.0, 2, 2) + 'kg'
      },
      features: [
        Mock.Random.csentence(10, 20),
        Mock.Random.csentence(10, 20),
        Mock.Random.csentence(10, 20),
        Mock.Random.csentence(10, 20)
      ],
      createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
    })
  }
  
  return products
}

// 生成用户数据
const generateUsers = () => {
  return {
    id: Mock.Random.id(),
    username: Mock.Random.cname(),
    email: Mock.Random.email(),
    phone: Mock.Random.string('number', 11),
    avatar: Mock.Random.image('100x100', Mock.Random.color(), '#FFF', 'Avatar'),
    gender: Mock.Random.pick(['male', 'female', 'other']),
    birthday: Mock.Random.date('yyyy-MM-dd'),
    bio: Mock.Random.cparagraph(1, 2),
    address: {
      name: Mock.Random.cname(),
      phone: Mock.Random.string('number', 11),
      province: Mock.Random.pick(['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省']),
      city: Mock.Random.pick(['北京市', '上海市', '广州市', '深圳市', '南京市', '杭州市', '成都市']),
      district: Mock.Random.pick(['朝阳区', '海淀区', '浦东新区', '黄浦区', '天河区', '福田区']),
      detail: Mock.Random.csentence(10, 20)
    },
    createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  }
}

// 生成订单数据
const generateOrders = (count = 20) => {
  const orders = []
  const products = globalProducts.length > 0 ? globalProducts : generateProducts(100)
  
  for (let i = 0; i < count; i++) {
    const orderProducts = []
    const productCount = Mock.Random.integer(1, 5)
    
    for (let j = 0; j < productCount; j++) {
      const product = products[Math.floor(Math.random() * products.length)]
      orderProducts.push({
        id: product.id,
        name: product.name,
        specification: `${product.specifications.颜色} ${product.specifications.尺寸}`,
        price: product.price,
        quantity: Mock.Random.integer(1, 5),
        image: product.images[0]
      })
    }
    
    const subtotal = orderProducts.reduce((sum, item) => sum + item.price * item.quantity, 0)
    const shippingFee = Mock.Random.float(0, 20, 2, 2)
    const discount = Mock.Random.float(0, subtotal * 0.3, 2, 2)
    const totalAmount = subtotal + shippingFee - discount
    
    orders.push({
      id: `ORD${Mock.Random.date('yyyyMMdd')}${Mock.Random.string('number', 3)}`,
      status: Mock.Random.pick(['pending', 'paid', 'shipped', 'delivered', 'completed', 'cancelled']),
      createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      payTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      shipTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      completeTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      paymentMethod: Mock.Random.pick(['支付宝', '微信支付', '银行卡', '现金']),
      subtotal: subtotal,
      shippingFee: shippingFee,
      discount: discount,
      totalAmount: totalAmount,
      products: orderProducts,
      address: {
        name: Mock.Random.cname(),
        phone: Mock.Random.string('number', 11),
        province: Mock.Random.pick(['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省']),
        city: Mock.Random.pick(['北京市', '上海市', '广州市', '深圳市', '南京市', '杭州市', '成都市']),
        district: Mock.Random.pick(['朝阳区', '海淀区', '浦东新区', '黄浦区', '天河区', '福田区']),
        detail: Mock.Random.csentence(10, 20)
      },
      logistics: {
        company: Mock.Random.pick(['顺丰速运', '圆通速递', '中通快递', '申通快递', '韵达快递', 'EMS']),
        trackingNumber: Mock.Random.string('upper', 10, 15),
        tracks: [
          {
            time: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
            content: '已签收，签收人：' + Mock.Random.cname()
          },
          {
            time: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
            content: '快件已到达【' + Mock.Random.pick(['北京', '上海', '广州', '深圳']) + '营业点】'
          },
          {
            time: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
            content: '快件在【' + Mock.Random.pick(['北京', '上海', '广州', '深圳']) + '转运中心】完成分拣'
          },
          {
            time: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
            content: '快件已从【' + Mock.Random.pick(['北京', '上海', '广州', '深圳']) + '营业点】发出'
          }
        ]
      }
    })
  }
  
  return orders
}

// 生成收藏数据
const generateFavorites = (count = 10) => {
  const favorites = []
  const products = generateProducts(count)
  
  for (let i = 0; i < count; i++) {
    favorites.push({
      id: products[i].id,
      name: products[i].name,
      price: products[i].price,
      image: products[i].images[0]
    })
  }
  
  return favorites
}

// 生成地址数据
const generateAddresses = (count = 3) => {
  const addresses = []
  
  for (let i = 0; i < count; i++) {
    addresses.push({
      id: i + 1,
      name: Mock.Random.cname(),
      phone: Mock.Random.string('number', 11),
      province: Mock.Random.pick(['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省']),
      city: Mock.Random.pick(['北京市', '上海市', '广州市', '深圳市', '南京市', '杭州市', '成都市']),
      district: Mock.Random.pick(['朝阳区', '海淀区', '浦东新区', '黄浦区', '天河区', '福田区']),
      detail: Mock.Random.csentence(10, 20)
    })
  }
  
  return addresses
}

// 模拟API接口
export const mockApi = {
  // 获取商品列表
  getProducts: (params = {}) => {
    const { page = 1, pageSize = 20, category, keyword, sortBy } = params
    let products = [...globalProducts]
    
    // 分类筛选
    if (category) {
      products = products.filter(item => item.category === category)
    }
    
    // 关键词搜索
    if (keyword) {
      products = products.filter(item => 
        item.name.includes(keyword) || item.description.includes(keyword)
      )
    }
    
    // 排序
    if (sortBy) {
      switch (sortBy) {
        case 'price-asc':
          products.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          products.sort((a, b) => b.price - a.price)
          break
        case 'rating':
          products.sort((a, b) => b.rating - a.rating)
          break
        case 'sales':
          products.sort((a, b) => b.sales - a.sales)
          break
        default:
          break
      }
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const paginatedProducts = products.slice(start, end)
    
    return {
      code: 200,
      message: 'success',
      data: {
        list: paginatedProducts,
        total: products.length,
        page,
        pageSize
      }
    }
  },
  
  // 获取商品详情
  getProductDetail: (id) => {
    // 从全局商品数据中查找
    const product = globalProducts.find(p => p.id === parseInt(id))
    if (product) {
      return {
        code: 200,
        message: 'success',
        data: product
      }
    } else {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      }
    }
  },
  
  // 获取商品分类
  getCategories: () => {
    return {
      code: 200,
      message: 'success',
      data: globalCategories
    }
  },
  
  // 用户登录
  login: (credentials) => {
    const { username, password } = credentials
    
    // 查找固定用户
    const user = globalUsers.find(u => u.username === username)
    
    if (user && password) {
      // 为每个用户生成唯一的token
      const token = `token_${user.id}_${Mock.Random.string('lower', 16)}`
      
      return {
        code: 200,
        message: '登录成功',
        data: {
          user,
          token
        }
      }
    } else {
      return {
        code: 400,
        message: '用户名或密码错误',
        data: null
      }
    }
  },
  
  // 用户注册
  register: (userData) => {
    const user = generateUsers()
    return {
      code: 200,
      message: '注册成功',
      data: {
        user,
        token: Mock.Random.string('lower', 32)
      }
    }
  },
  
  // 获取用户信息
  getUserInfo: (token) => {
    // 从token中提取用户ID
    const tokenMatch = token.match(/token_(\d+)_/)
    if (!tokenMatch) {
      return {
        code: 401,
        message: '无效的token',
        data: null
      }
    }
    
    const userId = parseInt(tokenMatch[1])
    const user = globalUsers.find(u => u.id === userId)
    
    if (user) {
      return {
        code: 200,
        message: 'success',
        data: user
      }
    } else {
      return {
        code: 404,
        message: '用户不存在',
        data: null
      }
    }
  },
  
  // 更新用户信息
  updateUserInfo: (userData) => {
    return {
      code: 200,
      message: '更新成功',
      data: generateUsers()
    }
  },
  
  // 获取订单列表
  getOrders: (params = {}) => {
    const { status, page = 1, pageSize = 10 } = params
    let orders = [...globalOrders]
    
    if (status && status !== 'all') {
      orders = orders.filter(order => order.status === status)
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const paginatedOrders = orders.slice(start, end)
    
    return {
      code: 200,
      message: 'success',
      data: {
        list: paginatedOrders,
        total: orders.length,
        page,
        pageSize
      }
    }
  },
  
  // 获取订单详情
  getOrderDetail: (id) => {
    const orders = generateOrders(1)
    const order = orders[0]
    order.id = id
    
    return {
      code: 200,
      message: 'success',
      data: order
    }
  },
  
  // 获取收藏列表
  getFavorites: (token) => {
    // 从token中提取用户ID
    const tokenMatch = token.match(/token_(\d+)_/)
    if (!tokenMatch) {
      return {
        code: 401,
        message: '无效的token',
        data: []
      }
    }
    
    const userId = parseInt(tokenMatch[1])
    const userFavs = userFavorites[userId] || []
    
    return {
      code: 200,
      message: 'success',
      data: userFavs
    }
  },
  
  // 添加收藏
  addFavorite: (productId, token) => {
    // 从token中提取用户ID
    const tokenMatch = token.match(/token_(\d+)_/)
    if (!tokenMatch) {
      return {
        code: 401,
        message: '无效的token',
        data: null
      }
    }
    
    const userId = parseInt(tokenMatch[1])
    
    // 检查商品是否已收藏
    const existingFavorite = userFavorites[userId]?.find(f => f.id === parseInt(productId))
    if (existingFavorite) {
      return {
        code: 400,
        message: '商品已在收藏列表中',
        data: null
      }
    }
    
    // 从全局商品中查找商品
    const product = globalProducts.find(p => p.id === parseInt(productId))
    if (!product) {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      }
    }
    
    // 添加到用户收藏列表
    const newFavorite = {
      id: parseInt(productId),
      name: product.name,
      description: product.description,
      price: product.price,
      originalPrice: product.originalPrice,
      images: product.images,
      rating: product.rating,
      reviews: product.reviews,
      stock: product.stock,
      addTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
    }
    
    if (!userFavorites[userId]) {
      userFavorites[userId] = []
    }
    userFavorites[userId].push(newFavorite)
    
    return {
      code: 200,
      message: '添加收藏成功',
      data: newFavorite
    }
  },
  
  // 删除收藏
  removeFavorite: (productId, token) => {
    // 从token中提取用户ID
    const tokenMatch = token.match(/token_(\d+)_/)
    if (!tokenMatch) {
      return {
        code: 401,
        message: '无效的token',
        data: null
      }
    }
    
    const userId = parseInt(tokenMatch[1])
    
    if (!userFavorites[userId]) {
      return {
        code: 404,
        message: '收藏商品不存在',
        data: null
      }
    }
    
    const index = userFavorites[userId].findIndex(f => f.id === parseInt(productId))
    if (index === -1) {
      return {
        code: 404,
        message: '收藏商品不存在',
        data: null
      }
    }
    
    userFavorites[userId].splice(index, 1)
    
    return {
      code: 200,
      message: '删除收藏成功',
      data: null
    }
  },
  
  // 检查是否已收藏
  checkFavorite: (productId, token) => {
    // 从token中提取用户ID
    const tokenMatch = token.match(/token_(\d+)_/)
    if (!tokenMatch) {
      return {
        code: 401,
        message: '无效的token',
        data: { isFavorite: false, productId: parseInt(productId) }
      }
    }
    
    const userId = parseInt(tokenMatch[1])
    const isFavorite = userFavorites[userId]?.some(f => f.id === parseInt(productId)) || false
    
    return {
      code: 200,
      message: 'success',
      data: {
        isFavorite,
        productId: parseInt(productId)
      }
    }
  },
  
  // 获取地址列表
  getAddresses: () => {
    return {
      code: 200,
      message: 'success',
      data: globalAddresses
    }
  },
  
  // 搜索商品
  searchProducts: (keyword) => {
    const products = generateProducts(50)
    const filteredProducts = products.filter(item => 
      item.name.includes(keyword) || item.description.includes(keyword)
    )
    
    return {
      code: 200,
      message: 'success',
      data: filteredProducts
    }
  },
  
  // 获取轮播图
  getBanners: () => {
    const banners = []
    for (let i = 1; i <= 5; i++) {
      banners.push({
        id: i,
        title: Mock.Random.ctitle(5, 15),
        image: `https://picsum.photos/1200/400?random=${i + 100}`,
        link: `/product/${Mock.Random.integer(1, 100)}`,
        sort: i
      })
    }
    
    return {
      code: 200,
      message: 'success',
      data: banners
    }
  },
  
  // 获取公告
  getAnnouncements: () => {
    const announcements = []
    for (let i = 1; i <= 5; i++) {
      announcements.push({
        id: i,
        title: Mock.Random.ctitle(10, 25),
        content: Mock.Random.cparagraph(1, 2),
        date: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
        type: Mock.Random.pick(['notice', 'promotion', 'maintenance']),
        isTop: Mock.Random.boolean()
      })
    }
    
    return {
      code: 200,
      message: 'success',
      data: announcements
    }
  }
}

// 配置Mock接口
// 注意：商品详情接口必须在商品列表接口之前，因为正则表达式匹配顺序很重要
Mock.mock(/\/api\/products\/\d+/, 'get', (options) => {
  const id = options.url.match(/\/products\/(\d+)/)[1]
  console.log('Mock: 匹配到商品详情接口，ID:', id)
  return mockApi.getProductDetail(id)
})

Mock.mock(/\/api\/products/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const params = Object.fromEntries(url.searchParams)
  console.log('Mock: 匹配到商品列表接口，参数:', params)
  return mockApi.getProducts(params)
})

Mock.mock(/\/api\/categories/, 'get', () => {
  return mockApi.getCategories()
})

Mock.mock(/\/api\/auth\/login/, 'post', (options) => {
  const body = JSON.parse(options.body)
  return mockApi.login(body)
})

Mock.mock(/\/api\/auth\/register/, 'post', (options) => {
  const body = JSON.parse(options.body)
  return mockApi.register(body)
})

Mock.mock(/\/api\/user\/info/, 'get', (options) => {
  const token = options.headers?.Authorization?.replace('Bearer ', '') || ''
  return mockApi.getUserInfo(token)
})

Mock.mock(/\/api\/user\/update/, 'put', (options) => {
  const body = JSON.parse(options.body)
  return mockApi.updateUserInfo(body)
})

Mock.mock(/\/api\/orders/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const params = Object.fromEntries(url.searchParams)
  return mockApi.getOrders(params)
})

Mock.mock(/\/api\/orders\/\w+/, 'get', (options) => {
  const id = options.url.match(/\/orders\/(\w+)/)[1]
  return mockApi.getOrderDetail(id)
})

Mock.mock(/\/api\/favorites/, 'get', (options) => {
  const token = options.headers?.Authorization?.replace('Bearer ', '') || ''
  return mockApi.getFavorites(token)
})

Mock.mock(/\/api\/favorites/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const token = options.headers?.Authorization?.replace('Bearer ', '') || ''
  return mockApi.addFavorite(body.productId, token)
})

Mock.mock(/\/api\/favorites\/\d+/, 'delete', (options) => {
  const id = options.url.match(/\/favorites\/(\d+)/)[1]
  const token = options.headers?.Authorization?.replace('Bearer ', '') || ''
  return mockApi.removeFavorite(id, token)
})

Mock.mock(/\/api\/favorites\/check\/\d+/, 'get', (options) => {
  const id = options.url.match(/\/favorites\/check\/(\d+)/)[1]
  const token = options.headers?.Authorization?.replace('Bearer ', '') || ''
  return mockApi.checkFavorite(id, token)
})

Mock.mock(/\/api\/addresses/, 'get', () => {
  return mockApi.getAddresses()
})

Mock.mock(/\/api\/search/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const keyword = url.searchParams.get('q')
  return mockApi.searchProducts(keyword)
})

Mock.mock(/\/api\/system\/banners/, 'get', () => {
  return mockApi.getBanners()
})

Mock.mock(/\/api\/system\/announcements/, 'get', () => {
  return mockApi.getAnnouncements()
})

// 初始化全局数据
initializeGlobalData()

export default Mock 